<?php	
	require "db.inc";
	$conn = new mysqli($host, $username, $password, $dbname);	
	$conn->query("set names 'utf8'");	
	

	$userName = $_REQUEST["txtName"];
	$passOrigin = $_REQUEST["txtPass"];
	$chkSave = $_REQUEST["chkSave"];
	$passWord = md5($passOrigin);	
	$strSQL = "call sp_LogIn('$userName', '$passWord')";	
	$result = $conn->query($strSQL);	
	$conn->close();
	
	if(mysqli_num_rows($result))
	{
		$row = $result->fetch_row();
		$id	= $row[0];
		
		//check useronline
		$mysqli = new mysqli($host, $username, $password,$dbname);
		$query = "call sp_GetUserOnline('$id')";
		$result = $mysqli->query($query);
		if(mysqli_num_rows($result))
		{
			header('Location: ../common/login.php?error=2');
			exit();
		}
		
		//add user online
		session_start(); 
		$session=session_id(); 
		$time=time();
		$mysqli = new mysqli($host, $username, $password,$dbname);
		$query = "call sp_AddUserOnline('$id', '$time')";
		$result = $mysqli->query($query);
		$mysqli->close();		
		
		$userName = $row[1];
		$passWord = $row[2];		
		$email = $row[3];
		$type = $row[4];
		$mana = $row[5];
		$status = $row[6];
		
		$_SESSION["user_id"] = $id;
		$_SESSION["user_name"] = $userName;
		$_SESSION["user_mana"] = $mana;
		
		if($chkSave == "on")
		{
			setcookie("user_name", $userName, time() + 3600*24*30);
			setcookie("user_pass", $passOrigin, time() + 3600*24*30);
			setcookie("chk_save", $chkSave, time() + 3600*24*30);			
		}
		else
		{
			setcookie("user_name", "", time()-3600);
			setcookie("user_pass", "", time()-3600);
			setcookie("chk_save", $chkSave, time()-3600);
		}
				
		
		if($status == 1)
		{
			if($type == 1)
			{
				header("Location: ../admin/home.php");
			}
			else if($type == 0)
			{
				header("Location: ../user/home.php");
			}
		}
		else
		{
			header("Location: login.php?error=3");				
		}
	}
	else
	{
		//Sai userName hoặc passWord! Vui lòng nhập lại.
		setcookie("chk_save");
		header("Location: login.php?error=1");		
	}
	

?>
